package gui.android;

import game.Charakter;

import java.util.ArrayList;
import java.util.Arrays;

import database.dbCharacterImpl;
import database.dbTempImpl;
import perv_comp.abbs.cok.R;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import animal.Animal;

public class Opponent_List extends Activity implements OnClickListener {

	private Button backButton;
	private Button continueButton;
	ListView lvMain;
	private String DBNAME = "PERSONS.db";
	private String TABLE = "MY_TABLE";
	private ArrayList<Charakter> enemiesList = new ArrayList();
	private ImageView myAnimalView;
	private ImageView enemyAnimalView;
	private TextView myStatsView;
	private TextView enemyStatsView;
	int myUserID = 0;
	int myAnimalID = 0;
	int selectedEnemyID = 0;
	int selectedEnemyAnimalID = 0;
	int gameIDGlobal=0;
	ArrayAdapter<String> enemyListAdapter;
	SQLiteDatabase mydb;
	UIUpdater mUIUpdater;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
		setContentView(R.layout.activity_opponent__list);

		initializeViews();
		initializeButtons();
		// get user data
		getMyUserIDFromDB();
		getMyAnimalIDFromDB();

		// load Views

		loadMyImageView();

		// start List listener
		lvMainListener();

		// start Update Handler
		mUIUpdater = new UIUpdater(new Runnable() {
			@Override
			public void run() {

				getEnemiesFromDB();

			}
		});

		mUIUpdater.startUpdates();

	}

	private void initializeViews() {
		lvMain = (ListView) findViewById(R.id.oponnentListView);
		myAnimalView = (ImageView) findViewById(R.id.oppListMyAnimal);
		enemyAnimalView = (ImageView) findViewById(R.id.oppListEnemyAnimal);
		myStatsView = (TextView) findViewById(R.id.myStatsOppChoice);
		enemyStatsView = (TextView) findViewById(R.id.enemyStatsOppChoice);

	}

	private void initializeButtons() {
		backButton = (Button) findViewById(R.id.zuruck);
		continueButton = (Button) findViewById(R.id.startgame);

		backButton.setOnClickListener(this);
		continueButton.setOnClickListener(this);

	}

	private void getEnemiesFromDB() {
		enemiesList.clear();
		dbCharacterImpl dbC = new dbCharacterImpl();
		String[] enemies = dbC.getActiveEnemies();
		ArrayList<Charakter> enemiesListFull = new ArrayList();
		for (int i = 0; i < enemies.length; i++) {
			String[] substr = enemies[i].split("-");
			int enemyAnimalID = Integer.parseInt(substr[0]);
			int enemyID = Integer.parseInt(substr[1]);
			
			int gameID = Integer.parseInt(substr[2]);
			String enemyName = substr[3];
			
			
			enemiesListFull.add(new Charakter(enemyID, enemyName,
					enemyAnimalID, gameID));
			
			if (enemyID != myUserID) {
				enemiesList.add(new Charakter(enemyID, enemyName,
						enemyAnimalID, gameID));
			}
			if (enemyID == myUserID && gameID != 0) {
				gameIDGlobal=gameID;						
			}

		}
		
		if(gameIDGlobal!=0){
			getEnemy(enemiesListFull,gameIDGlobal);
		}

		
		String[] enemyList = new String[enemiesList.size()];

		for (int i = 0; i < enemiesList.size(); i++) {
			enemyList[i] = enemiesList.get(i).getName();
		}
		enemyListAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, enemyList);
		lvMain.setAdapter(enemyListAdapter);
	}

	private void getEnemy(ArrayList<Charakter> enemiesListFull, int gameID) {
		for (int j = 0; j < enemiesListFull.size(); j++) {
			if(enemiesListFull.get(j).getGameID()==gameIDGlobal
					&& enemiesListFull.get(j).getCharID()!=myUserID){
				mUIUpdater.stopUpdates();
				setDataLocal(enemiesListFull.get(j).getCharID(),enemiesListFull.get(j).getAnimalID(),gameIDGlobal);
				setRolle(2);
				herausgefordertDialog();
				setPlayerInactive(enemiesListFull.get(j));
				break;
			}
		}
		}
		
	

	private void setPlayerInactive(Charakter charakter) {
		dbCharacterImpl dbC = new dbCharacterImpl();
		dbC.setCharActive(myAnimalID, myUserID, 0);
		dbC.setCharActive(charakter.getAnimalID(), charakter.getCharID(), 0);	
	}

	private void setRolle(int rolle) {
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		mydb.execSQL("UPDATE " + TABLE + " SET ROLLE='" + rolle+"'");
		mydb.close();
		
	}



	private void getMyUserIDFromDB() {
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor c = mydb.rawQuery("SELECT * FROM " + TABLE, null);
		c.moveToFirst();
		myUserID = c.getInt(0);
		c.close();
		mydb.close();

	}

	private void getMyAnimalIDFromDB() {
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor c = mydb.rawQuery("SELECT * FROM " + TABLE, null);
		c.moveToFirst();
		myAnimalID = c.getInt(2);
		
		c.close();
		mydb.close();

	}

	private void loadMyImageView() {

		Animal myAnimal = new Animal().getAnimalOverID(myAnimalID);

		myAnimalView.setImageDrawable(getResources().getDrawable(
				myAnimal.getMyAnimalGrafik()));
		myStatsView.setText(Html.fromHtml(myAnimal.getAnimalStatsHtmlString()));

	}

	private void lvMainListener() {
		lvMain.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> myAdapter, View myView,
					int myItemInt, long mylng) {
				Animal myAnimal = new Animal().getAnimalOverID(enemiesList.get(
						myItemInt).getAnimalID());
				int newselectedEnemyID = enemiesList.get(myItemInt).getCharID();
				int newselectedEnemyAnimalID = enemiesList.get(myItemInt)
						.getAnimalID();
				if (newselectedEnemyID != selectedEnemyID
						| newselectedEnemyAnimalID != selectedEnemyAnimalID) {
					enemyAnimalView.setImageDrawable(getResources()
							.getDrawable(myAnimal.getEnemyAnimalGrafik()));
					enemyStatsView.setText(Html.fromHtml(myAnimal
							.getAnimalStatsHtmlString()));
					selectedEnemyAnimalID = newselectedEnemyAnimalID;
					selectedEnemyID = newselectedEnemyID;
				}

			}
		});

	}

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		// getMenuInflater().inflate(R.menu.opponent__list, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		mUIUpdater.stopUpdates();	

		switch (v.getId()) {
		case R.id.zuruck:
			// disableChar();
			Intent intent = new Intent(this, MyCharacter.class);
			startActivity(intent);
			break;
		case R.id.startgame:
			if (selectedEnemyID == 0) {
				noOpponentAlertDialog();
				break;
			} else {
				int gameID = (int) (234 * Math.random() + 23);
			
				setDataLocal(selectedEnemyID,selectedEnemyAnimalID,gameID);
				setDataOnline(selectedEnemyID,selectedEnemyAnimalID,gameID);
				prepareGame(gameID);
				setRolle(1);
				showGame();
				break;
			}

		}
	}

	private void setDataLocal(int charID, int animalID, int gameID) {
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		mydb.execSQL("UPDATE " + TABLE + " SET OPPONENTID='" + charID
				+ "',"+" OPPONENTANIMAL='"+animalID+"'");
		mydb.execSQL("UPDATE " + TABLE + " SET GAMEID='" + gameID+"'");
		mydb.close();
		
	}
	private void setDataOnline(int selectedEnemyID,int selectedEnemyAnimalID, int gameID) {
		dbCharacterImpl dbC = new dbCharacterImpl();
		dbC.setGameID(selectedEnemyAnimalID, selectedEnemyID, gameID);
		dbC.setGameID(myAnimalID, myUserID, gameID);
		
	}

	private void noOpponentAlertDialog() {
		AlertDialog.Builder dialog2 = new AlertDialog.Builder(this);
		dialog2.setTitle("Angsthase!");
		dialog2.setMessage(Html
				.fromHtml("W&auml;hle einen Gegner aus der Liste<br>"
						+ "Sind noch keine da, warte kurz!"));
		dialog2.setCancelable(false);
		dialog2.setIcon(getResources().getDrawable(R.drawable.cancel));

		dialog2.setNegativeButton("Ok", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface d, int id) {

				d.cancel();
			}

		});
		AlertDialog alertDialog2 = dialog2.create();
		alertDialog2.show();

	}

	private void herausgefordertDialog() {
		AlertDialog.Builder herausForderungsDialog = new AlertDialog.Builder(
				this);
		herausForderungsDialog.setTitle("Herausgefordert!");
		herausForderungsDialog.setMessage(Html
				.fromHtml("Sie wurden herausgefordert!<br>"
						+ "Verteidigen Sie sich!"));
		herausForderungsDialog.setCancelable(false);
		herausForderungsDialog.setIcon(getResources().getDrawable(
				R.drawable.deficon));

		herausForderungsDialog.setPositiveButton(("Ja!"),
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface d, int id) {

						showGame();

					}

				});

		AlertDialog rausforderungDialog = herausForderungsDialog.create();
		rausforderungDialog.show();

	}

	private void showGame() {
		Intent intent = new Intent(this, GroundOFGame.class);
		startActivity(intent);

	}

	private void prepareGame(int gameID) {
	
		dbTempImpl dbT = new dbTempImpl();
		dbT.createTemp(gameID);
		dbT.addRunde(gameID, 1, 1000, 1000, 0, 0);
//		dbT.setRunde(gameID,1);

		mydb.close();
	}
}